package sh.ds.el.dao.jdbc;

import java.io.Serializable;
import java.util.List;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sh.ds.el.common.Constants;

public class DefaultHibernateOrmExecution extends DefaultSqlExceution implements HibernateOrmExecution {

	private HibernateTemplate hibernateTemplate;
    
	protected HibernateTemplate getHibernateTemplate() {
        return this.hibernateTemplate;
    }
	
	public DefaultHibernateOrmExecution(DataSource dataSource, SessionFactory sessionFactory) {
		super(dataSource);
		
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@SuppressWarnings("unchecked")
	public <T> T getEntity(Class<T> entityClass, Serializable id) {
		return (T) getHibernateTemplate().get(entityClass, id);
	}
	
	public void doSave(Object entity) {
		getHibernateTemplate().save(entity);
	}
	
	public void doUpdate(Object entity) {
		getHibernateTemplate().update(entity);
	}
	
	public void doSaveOrUpdate(Object entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}
	
	public void doDelete(Object entity) {
		getHibernateTemplate().delete(entity);
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> find(Class<T> returnType, String hql, List<Object> params) {
		Object[] args = Constants.EMPTY_OBJECT_ARRAY;
		if (params != null) {
			args = params.toArray();
		}
		return getHibernateTemplate().find(hql, args);
	}
	
}
